import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { asyncRoutes } from '@/router/dynamicRoute'


Vue.use(Router)

/* Layout */
import Layout from '@/layout'

export const staticRoutes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/workbench'
    // redirect: '/login'
  },
  {
    path: '/workbench',
    component: Layout,
    children: [{
      //特殊的二级路由(等价于一级路由)
      path: '',

      //用函数动态导入
      component: () => import('@/views/Workbench/index'),
      meta: { title: '工作台', icon: 'el-icon-data-board' }
    }]
  },

  //添加新增月卡界面的路由
  {
    path: '/cardAdd',
    component: () => import('@/views/Car/CarCard/cardAdd'),
    hidden: true
  },
  //编辑月卡界面的路由
  {
    path: '/cardEdit',
    component: () => import('@/views/Car/CarCard/cardEdit'),
    hidden: true
  },
  //续费月卡界面的路由
  {
    path: '/cardRenew',
    component: () => import('@/views/Car/CarCard/cardRenew'),
    hidden: true
  },
  //新增企业界面的路由
  {
    path: '/enterpriseAdd',
    component: () => import('@/views/Park/Enterprise/enterpriseAdd'),
    hidden: true
  },
  //编辑企业页面路由
  {
    path: '/enterpriseEdit',
    component: () => import('@/views/Park/Enterprise/enterpriseEdit'),
    hidden: true
  },
  //查看企业详情界面的路由
  {
    path: '/enterpriseDetail',
    component: () => import('@/views/Park/Enterprise/enterprisePrev')
  },
  //系统管理添加用户的路由
  {
    path: '/roleAdd',
    component: () => import('@/views/System/Role/addRole.vue')
  },
  //系统管理编辑用户的路由
  {
    path: '/roleEdit',
    component: () => import('@/views/System/Role/editRole.vue')
  },
  //网页丢失路由
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },


]
// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}
// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 根据权限标识过滤路由表
/** * 
 * @param {*} firstRoutePerms ['park','parking',...]
 * @param {*} secondRoutePerms  ['park:building','parking:area',...]
 * @param {*} asyncRoutes 动态路由规则表
 * @returns 
 */
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}

const createRouter = () => new Router({
  // mode: 'history', // require service support
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: staticRoutes
})
const router = createRouter()
//路由守卫
router.beforeEach(async (to, from, next) => {
  const token = store.state.user.token
  if (to.path === '/login') {
    next()
  } else {
    if (token) {
      // 获取权限列表
      next()

      if (!store.state.user.profile.id) {
        const permissions = await store.dispatch('user/getProfile')
        console.log('权限列表', permissions);

        // 处理一级和二级菜单标识
        const firstRoutePerms = getFirstRoutePerms(permissions)
        console.log(firstRoutePerms)
        const secondRoutePerms = getSecondRoutePerms(permissions)
        console.log(secondRoutePerms)

         // 根据权限标识过滤路由表
         const filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
         //addRoute动态添加路由
         // '*:*:*' 表示管理员，拥有所有的权限
         if (permissions.includes('*:*:*')) {
             // 添加路由
             asyncRoutes.forEach(item => router.addRoute(item))
            await store.commit('menu/setMenuList', asyncRoutes)                  
         } else {
             // 添加路由
             filterRoutes.forEach(item => router.addRoute(item))
            await store.commit('menu/setMenuList', filterRoutes)                  
         }
      }
    } else {
      next('/login')
    }
  }
})

// 重置路由方法
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter()
  // 使用新的路由记录覆盖掉老的路由记录
  router.matcher = newRouter.matcher
}

export default router
